package com.iflytek.uoamp.notify.core.handler;

/**
 * @author LongJun Song
 * @version 1.0.0
 * Create Date 2014-11-13
 */

import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.CharsetUtil;

public class ResponseHelper {

	/**
	 * 返回请求内容给Http的请求端
	 * 
	 * @param ctx
	 * @param status
	 */
	public static HttpResponse getResponse(ChannelHandlerContext ctx, String body) {
		StringBuilder builder = new StringBuilder();
		builder.append(body);
		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
		response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
		response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
		response.content().writeBytes(Unpooled.copiedBuffer(builder.toString(), CharsetUtil.UTF_8));
		return response;
	}
	
	
	/**
	 * 发送结果到客户端
	 * @param ctx
	 * @param body
	 */
	public static void send(ChannelHandlerContext ctx, HttpResponse body) {
		Channel ch = ctx.channel();
		if (ch.isOpen()) {
			ctx.writeAndFlush(body).addListener(ChannelFutureListener.CLOSE);
		}
	}
}
